import SwiftUI
import CoreGraphics

struct PieChartView: View {
    @Binding var dataPoints: [String]
    @Binding var dataValues: [Double]
    
    let center = CGPoint(x: UIScreen.main.bounds.width / 2 - 20, y: (UIScreen.main.bounds.height / 2) - 350)
    let radius: CGFloat = min(UIScreen.main.bounds.width, UIScreen.main.bounds.height) * 0.24
    
    var body: some View {
        let totalValue = dataValues.reduce(0, +)
        HStack(spacing: 10){
            ZStack(alignment: .center) {
                ForEach(0..<dataPoints.count, id: \.self) { index in
                    let startAngle = index == 0 ? 0 : dataValues[0..<index].reduce(0, +) * 2 * .pi
                    let endAngle = startAngle + dataValues[index] * 2 * .pi
                    
                    Path { path in
                        path.move(to: center)
                        path.addArc(center: center, radius: radius, startAngle: Angle(radians: Double(startAngle)), endAngle: Angle(radians: Double(endAngle)), clockwise: false)
                    }
                    .fill(colors[index])
                }
                .offset(x:-120,y:20)
                
                VStack (alignment: .leading){
                    ForEach(0..<dataPoints.count, id: \.self) { index in
                        if !dataValues[index].isNaN {
                            createChartItem(index: index, totalValue: totalValue)
                        }
                    }
                }
                .offset(x:90,y:-30)
            }
        }
            
    }
    
    private func createChartItem(index: Int, totalValue: Double) -> some View {
        let color = colors[index]
        let dataPoint = dataPoints[index]
        let value = dataValues[index]
        let percentage = (value / totalValue) * 100
        
        return HStack(spacing: 5) {
            Rectangle()
                .fill(color)
                .frame(width: 10, height: 10)
                .alignmentGuide(HorizontalAlignment.center) { _ in
                    return 0.5
                }
            
            Text(dataPoint)
                .rotationEffect(.degrees(0))
                .font(.system(size: 13))
                .lineLimit(1)
                .minimumScaleFactor(0.5)
                .multilineTextAlignment(.leading)
            
            if !value.isNaN && !percentage.isNaN {
                Text(String(format: "%.1f%%", percentage))
                    .font(.system(size: 13))
                    .multilineTextAlignment(.trailing)
            }
        }
    }
}

//struct PieChartView_Previews: PreviewProvider {
//    static var previews: some View {
//        ContentView()
//    }
//}

